//
//  CZComposeViewController.swift
//  GZWeibo666
//
//  Created by Apple on 15/12/4.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD

// 导航栏上面显示的内容部是有导航栏决定的,由当前正在显示的子控制器决定的

// @objc 让OC可以调用.除了privater以外都会自动加载@objc

class CZComposeViewController: UIViewController {
    
    // 属性
    /// toolBar底部约束
    private var toolBarBottomCon: NSLayoutConstraint?
    
    /// 照片选择器view的底部约束
    private var photoSelectorViewBottomCon: NSLayoutConstraint?
    
    /// 微博内容长度
    private let StatusLength = 20

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置背景颜色,不然,在Modal出来的时候,会看到后面的内容
        view.backgroundColor = UIColor.whiteColor()
        prepareUI()
        
        // 将自定义键盘的控制器管理起来
        addChildViewController(emoticonVC)
        
        print("键盘view: \(textView.inputView)")
        
        // 监听键盘的弹出和关闭
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 弹出键盘,在这里弹出来会有问题
//        textView.becomeFirstResponder()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 如果,照片选择器正在显示,就不需要主动弹出键盘
        if photoSelectorViewBottomCon?.constant != 0 {
            // 弹出键盘
            textView.becomeFirstResponder()
        }
    }
    
    /*
        willChangeFrame: NSConcreteNotification 0x7fa482c24790 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";    // 动画时间
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";   // 键盘最终的位置
        UIKeyboardIsLocalUserInfoKey = 1;
        }} 
    */

    // 监听键盘的frame将要改变
    func willChangeFrame(notification: NSNotification) {
//        print("willChangeFrame: \(notification)")
        
        // 动画时间
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        // 键盘的最终位置
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        
        // toolBar动画到指定的位置
        // toolBar底部约束的值 = 屏幕的高度 - 键盘frame.origin.y
        toolBarBottomCon?.constant = -(UIScreen.height() - endFrame!.origin.y)
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 准备UI
    private func prepareUI() {
        setupNAV()
        setupTextView()
        setupPhotoSelector()
        setupToolBar()
        setupLengthTipLabel()
    }

    /// 设置导航栏
    private func setupNAV() {
        // 左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        // 右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        
        // 设置发送按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitle()
    }
    
    /// 设置导航栏标题
    // 属性文本
    private func setupTitle() {
        // 前缀
        let pre = "发微博"
        
        // 获取用户名称
        if let name = CZUserAccount.loadUserAccount()?.screen_name {
            // 有名称, 拼接 换行 "\n"
            let title = pre + "\n" + name
            
            // 创建label
            let label = UILabel()
            
            label.font = UIFont.systemFontOfSize(14)
            
            label.numberOfLines = 0
            
            // 文字颜色
            label.textColor = UIColor.blackColor()
            
            // 居中
            label.textAlignment = NSTextAlignment.Center
            
            // 设置普通文本
//            label.text = title
            
            // 属性文本
            // NSAttributedString: 不可变
            // NSMutableAttributedString: 可变的
            let attrText = NSMutableAttributedString(string: title)
            
            // 获取 searchString 字符串在 title里面的范围
            let nameRange = (title as NSString).rangeOfString(name)
            
            // 添加属性,修改 用户名称 的文字颜色
            // name: 要添加的属性名称 NSForegroundColorAttributeName: 文字颜色
            // value: 属性的值
            // NSRange: 修改属性的范围
            attrText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            
            // 修改name的大小
            attrText.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: nameRange)
            
            // 设置属性文本
            label.attributedText = attrText
            
            // 适应大小
            label.sizeToFit()
            
            navigationItem.titleView = label
        } else {
            // 没有名称
            navigationItem.title = pre
        }
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 添加子控件
        view.addSubview(toolBar)
        
        // 添加约束
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.width(), height: 44))
        
        // 获取toolBar底部约束
        toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 添加按钮
        
        // 每个item对应的图片名称
        // 这个数组里面的每个元素是一个字典
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
//        var tag = 0
        
        // 存放 UIBarButtonItem
        var items = [UIBarButtonItem]()
        // 通过for遍历数组里面的图片名称
        for dict in itemSettings {
            // 获取到每个字典, 获取字典key为 imageName value, 图片的名称
            let imageName = dict["imageName"]!
            let item = UIBarButtonItem(imageName: imageName)
            
            // 从字典里面获取每一图片对应的方法名称
            let action = dict["action"]!
            
            // 获取UIBarButtonItem的customView(是一个按钮)
            let button = item.customView as! UIButton
            
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            
            // action: 如果是字符串,可以直接赋值.如果是变量或常量,需要 Selector(action)
//            button.addTarget(self, action: "itemClick", forControlEvents: UIControlEvents.TouchUpInside)
            
            // 给按钮添加tag,来区分是哪个按钮被点击了
//            button.tag = tag
            
            // 添加到toolBar里面
            items.append(item)
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
//            tag++
        }
        
        // 移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    /// 设置textView
    private func setupTextView() {
        // 添加子控件
        view.addSubview(textView)
        
        // 添加约束
        // 填充父控件
        textView.ff_Fill(view)
        
        // 自动适应顶部的边距
        // scrollView或子类会自动往下滚动64
        // 前提:scrollView或子类.所在的控制器,在导航控制器里面
        // scrollView或子类必须是 控制器的view 或者 是控制器view的第一个子view
//        automaticallyAdjustsScrollViewInsets = true
        
        // 设置代理,来监听textView文本的改变
        textView.delegate = self
    }
    
    /// 设置微博内容长度label
    private func setupLengthTipLabel() {
        // 添加子控件
        view.addSubview(lengthTipLabel)
        
        // 添加约束
        lengthTipLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    
    /// 设置照片选择器view
    private func setupPhotoSelector() {
        // 添加控件
        let photoSelectorView = photoSelectorVC.view
        view.addSubview(photoSelectorView)
        
        // 添加约束
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        
        // 宽度填充父控件
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["psv" : photoSelectorView]))
        
        // 高度 = 父控件的 60%
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.height() * 0.6))
        
        // 底部与父控件的底部重合
        photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: UIScreen.height() * 0.6)
        view.addConstraint(photoSelectorViewBottomCon!)
    }
    
    // MARK: - 按钮点击事件
    // toolBar上面的item被点击
    func picture() {
        // 弹出照片选择器的view,键盘退下
        photoSelectorViewBottomCon?.constant = 0
        
        // 动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        // 键盘退下
        view.endEditing(true)
    }
    
    func trend() {
        print("#")
    }
    
    func mention() {
        print("@")
    }
    
    /*
        在键盘弹出来之前.如果 textView.inputView == nil,弹出系统的键盘, textView.inputView != nil,就弹出对应的view
    */
    /// 切换表情键盘
    func emoticon() {
        print("表情键盘")
        
        // 先让键盘退回去
        textView.resignFirstResponder()
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 设置表情键盘,并不会立马切换键盘
            // 如果是系统键盘,就切换成自定义的键盘,如果是自定义的键盘,就切换到系统键盘
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
            
            // 再弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    func add() {
        print("+")
    }
    
    /// 关闭控制器
    @objc private func close() {
        // 关闭键盘
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发送微博, 连续两次发布的微博不可以重复
    @objc private func sendStatus() {
        // 需要获取到textView的文本内容.
        let status = textView.emoticonText()
        
        SVProgressHUD.showInfoWithStatus("正在发布微博...")
        
        // 判断是否超出长度
        let count = StatusLength - status.characters.count
        if count < 0 {
            // 微博内容超出长度
            SVProgressHUD.showErrorWithStatus("微博内容超出长度")
            return
        }
        
        // 获取image
        let image = photoSelectorVC.photos.first
        
        // 发布微博
        CZNetworkTool.sharedInstance.sendStatus(status, image: image) { (result, error) -> () in
            if error != nil {
                print("发布微博失败: \(error)")
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
//            print("result: \(result)")
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
                self.close()
            }
        }
    }
    
    // MARK: - 懒加载
    private lazy var toolBar: UIToolbar = {
        let bar = UIToolbar()
        
        bar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        return bar
    }()
    
    /*
        iOS可以让用户输入文本的控件:
            1.UITextField:
                1.有占位文本
                2.只能显示一行
                3.可以添加事件,不能滚动
    
            2.UITextView:
                1.没有占位文本
                2.可以显示多行
                3.可以滚动
    */
    private lazy var textView: CZPlaceholderTextView = {
        let tv = CZPlaceholderTextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        
        tv.backgroundColor = UIColor.brownColor()
        
        tv.alwaysBounceVertical = true
        
//        tv.text = "分享新鲜事......"
        
        // 设置占位文本
        tv.placeholder = "分享新鲜事"
        
        // 当拖动textView时,会让键盘退回去
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        
        return tv
    }()
    
    /// 自定义表请键盘的控制器
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController(textView: self.textView)
    
    /// 微博内容长度提示label
    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel(color: UIColor.lightGrayColor(), fontSize: 12)
        
        // 设置内容
        label.text = "\(self.StatusLength)"
        label.sizeToFit()
       
        return label
    }()
    
    /// 照片选择器控制器
    private lazy var photoSelectorVC: CZPhotoSelectorViewController = {
        let controller = CZPhotoSelectorViewController()
        
        // 添加到当前控制器的子控制器
        self.addChildViewController(controller)
        
        return controller
    }()
}

// 扩展 CZComposeViewController 实现 UITextViewDelegate,来监听文本的改变
extension CZComposeViewController: UITextViewDelegate {
    // 监听文本的改变
    func textViewDidChange(textView: UITextView) {
        // 设置导航栏右边按钮的状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 计算微博内容剩余长度
        let count = StatusLength - textView.emoticonText().characters.count
        
        let color = count < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
        lengthTipLabel.textColor = color
        lengthTipLabel.text = "\(count)"
        lengthTipLabel.sizeToFit()
    }
}
